// @before-stub-for-debug-begin
#include <vector>
#include <string>
#include "commoncppproblem123.h"

using namespace std;
// @before-stub-for-debug-end

/*
 * @lc app=leetcode.cn id=123 lang=cpp
 *
 * [123] 买卖股票的最佳时机 III
 */

// @lc code=start
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();
        vector<vector<int>> dp(3, vector<int>(2));
        
        for (int i = 0; i < n; ++i) {
            for (int k = 2; k >= 1; k--) {
                if (i == 0) {
                    dp[k][0] = 0;
                    dp[k][1] = -prices[i];
                    continue;
                }
                dp[k][0] = max(dp[k][0], dp[k][1] + prices[i]);
                dp[k][1] = max(dp[k][1], dp[k - 1][0] - prices[i]);
            }
        }
        return dp[2][0];
    }
};
// @lc code=end

